<template>
    <div class="dropdown" ref="button">
        <button class="btn btn-outline-light dropdown-toggle my-2" @click.prevent="showSlect" href="#" role="button"
            data-bs-toggle="dropdown" aria-expanded="false">
            {{ context }}
        </button>

        <ul class="dropdown-menu" :style="{ 'display': slectStuts ? 'block' : 'none' }">
            <li v-for="item, index in data" :key="index" class="dropdown-item"
                @click.prevent="slectClick(item, checkedDisabled(index))">
                <a href="#" :class="checkedDisabled(index) ? 'disabled' : ''">
                    {{ typeof item === 'string' ? item : item[valueKey ? valueKey : 'titel'] }}
                </a>
            </li>
        </ul>
    </div>
</template>

<script lang='ts'>
import { ref, defineComponent, PropType, watch } from 'vue'
import useHtmlShow from '../../hooks/useHtmlShow'
export type SlectProps = Array<{ [name: string]: any } | string>

export default defineComponent({
    name: 'DownSlect',
    props: {
        data: {
            type: Array as PropType<SlectProps>,
            required: true
        },
        valueKey: {
            type: String as PropType<string>,
        },
        context: {
            type: String,
            default: '默认文本'
        },
        disabled: {
            type: Array as PropType<number[]>,
            default: []
        }

    },
    emits: ["onButtonClick", "onSlict"],
    setup(props, { emit }) {
        const slectStuts = ref<boolean>(false)
        const button = ref<null | HTMLButtonElement>(null)
        const { disabled } = props
        const showSlect = () => {
            emit('onButtonClick')
            slectStuts.value = !slectStuts.value
        }
        const slectClick = (value: { [name: string]: any } | string, not?: boolean) => {
            if (not && button.value) {
                button.value.focus()
                return
            }
            emit('onSlict', value)
            slectStuts.value = false
        }
        const checkedDisabled = (value: number,) => {
            const result = disabled.findIndex(item => item === value) !== -1
            return result
        }
        const status = useHtmlShow(button)
        watch(status, (newValue) => {
            if (newValue && slectStuts) {
                slectStuts.value = false
            }
        })
        return { slectStuts, showSlect, slectClick, checkedDisabled, button }
    }
})
</script>
<style scoped lang="less">
a {
    text-decoration: none;
}

.disabled {
    color: grey !important;
    pointer-events: none !important;
    background-color: transparent !important;
}
</style>